package com.itsm.service;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.itsm.config.WeComProperties;
import com.itsm.entity.Approve;
import com.itsm.entity.Process;
import com.itsm.service.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
//消息推送逻辑实现
public class SendService {
    @Autowired
    private AccessTokenService accessTokenService;

    @Resource
    private WeComProperties properties;

    @Autowired
    private ProcessAllService processAllService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserMapper userMapper;

    public String sendMessage(String subject,String createName,String userId,String title,String url) throws IOException {

        String content = "<div class=\\\"blue\\\">问题类型："+subject+"</div>"+"\\n"+"创建人:"+createName;
        //构造消息体
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"touser\":" + "\"" + userId + "\",");
        sb.append("\"msgtype\":" + "\"" + "textcard" + "\",");
        sb.append("\"agentid\":" + "\"" + 1000023 + "\",");
        sb.append("\"textcard\":" + "{");
        sb.append("\"title\":" + "\"" + title + "\",");
        sb.append("\"description\":" + "\"" + content + "\",");
        sb.append("\"url\":" + "\"" + url + "\",");
        sb.append("\"btntxt\":" + "\"" + "查看详情" + "\"},");
        sb.append("\"safe\":\"0\"");
        sb.append("}");

        String token = accessTokenService.getAccessToken(properties.getCorpId(),properties.getCorpSecret());
        //请求链接
        String sendMessageUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
        //请求链接
        String action = sendMessageUrl + token;
        try {
            return HttpRequest.post(action)
                    .body(sb.toString())
                    .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }



    public String sendMobile(String json) throws IOException {


        String token = accessTokenService.getAccessToken(properties.getCorpId(),properties.getCorpSecret());
        //请求链接
        String sendMobileUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=";
        //请求链接
        String action = sendMobileUrl + token;

        try {
            return HttpRequest.post(action)
                    .body(json)
                    .execute().body();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 推送消息给审批人
     * @param process 工单信息
     * @param name 审批人
     * @return 空
     * @throws IOException
     */
    public void sendSup(Process process,String name) throws IOException {
        String userId = this.getUserId(name);
        String processNo = process.getProcessNo();
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String title = "有系统需求待您进行审批";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isCreate?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        this.sendMessage(subject,createName,userId,title,url);
    }

    /**
     * 推送给IT服务台，区分工厂
     * @param approve
     * @throws IOException
     */
    public void sendIT(Approve approve) throws IOException {
        String userId = userMapper.getUserByName(approve.getName()).getWxid();
        List<String> user = userMapper.getItSup1(userId);
        for (String id : user){
            String processNo = approve.getProcessNo();
            String createName = approve.getName();
            String subject = processAllService.select(processNo).getSubject();
            String title = "有系统需求待您进行审批";
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isCreate?processNo="  +processNo+
                    "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
            //发送消息
            this.sendMessage(subject,createName,id,title,url);
        }

    }

    /**
     * it服务台审批，区分工厂
     * @param process 工单信息
     * @throws IOException
     */
    public void sendDesk(Process process) throws IOException {
        List<String> user = userMapper.getItSup1(process.getUserid());
        for (String userId : user) {
            String processNo = process.getProcessNo();
            String createName = process.getCreateName();
            String subject = process.getSubject();
            String title = "有新的工单创建";
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isCreate?processNo=" + processNo +
                    "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
            //发送消息
            this.sendMessage(subject, createName, userId, title, url);
        }
//        String userId = properties.getSendId();//YinRuChenAi  ChenYingNan
    }

    public String sendUndistributed(Process process) throws IOException {
        String userId = properties.getSendId();//YinRuChenAi  ChenYingNan
        String processNo = process.getProcessNo();
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String title = "工单未指派";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isCreate?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    public String sendEn(Process process) throws IOException {
        String userId = this.getUserId(process.getRespaName());
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "有新的工单指派";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isAccept?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }
    public String sendUnaccepted(Process process) throws IOException {
        String userId = this.getUserId(process.getRespaName());
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "有指派的工单未接单";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isAccept?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    public String sendEnUndone(Process process) throws IOException {
        String userId = this.getUserId(process.getRespaName());
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "你有未完成的工单待完成";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isAccept?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }




    public String sendRate(Process process) throws IOException {
        String userId = this.getUserId(process.getRespaName());
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "你的工单已被评价";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/isAccept?processNo="  +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect\\";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    public String sendAccepted(Process process) throws IOException {
        String userId = process.getUserid();
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "您的工单已被接单";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/sendUser?processNo=" +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect";

        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    public String sendApprove(Approve approve) throws IOException {
        String processNo = approve.getProcessNo();
        String userId = processAllService.select(processNo).getUserid();
        String subject = processAllService.select(processNo).getSubject();
        String createName = processAllService.select(processNo).getCreateName();
        String title = "您的工单已被退回，请修改工单或删除！";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/sendUserAlter?processNo=" +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect";

        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    public String sendOver(Process process) throws IOException {
        String userId = process.getUserid();
        String createName = process.getCreateName();
        String subject = process.getSubject();
        String processNo = process.getProcessNo();
        String title = "您的工单已完成";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwfbc200b28be3408d&redirect_uri=http://itservice.hmjy-ic.com:8098/sendUser?processNo=" +processNo+
                "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000023#wechat_redirect";
        //发送消息
        return this.sendMessage(subject,createName,userId,title,url);
    }

    //通过姓名获取企业微信id
    public String getUserId(String name) throws IOException {
        String mobile = loginService.selectEnMobile(name);
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"mobile\":" + "\"" + mobile + "\",");
        sb.append("}");
        String user = this.sendMobile(sb.toString());
        JSONObject jsonObject = JSONObject.parseObject(user);
        return jsonObject.getString("userid");
    }







}
